//
//  PEDeviceDetailVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/27.
//

#import "RHEMSDetailVC.h"
#import "RHDeviceDetailStatusCell.h"
#import "RHDeviceDetailRiseCell.h"
#import "RHDeviceDetailProgressCell.h"
#import "SYChartTool.h"
#import "RHDevEMSModel.h"
#import "RHCommonDataCell.h"

@interface RHEMSDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSDictionary *dic;

@end

@implementation RHEMSDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = CFTabViewBgColor;
    [self createEMSDetailData];
    [self setupUI];
    [self getEmsDetail];
}

-(void)createEMSDetailData
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Dev_ems_detail"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHDevEMSModel class] json:arr];
}

-(void)setupUI{

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonStatusCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonIndicatorCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonProgressCell];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.estimatedRowHeight = 180;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getEmsDetail];
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 0, 0, 0));
    }];
}

#pragma mark -------- network -------

-(void)getEmsDetail
{
    [QMUITips showLoadingInView:self.view];
    NSMutableArray *keyCodes = [NSMutableArray array];
    [self.dataArr enumerateObjectsUsingBlock:^(RHDevEMSModel  *_Nonnull emsModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [emsModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if(dataModel.keyCode.length != 0){
                [keyCodes addObject:dataModel.keyCode];
            }
           
        }];
    }];
    [keyCodes addObject:@"Bty_TV"];
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":self.curEMSModel.type,
                           @"keyCodes":keyCodes,
                           @"endpointSn":self.curEMSModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
                __block RHDevDataModel *maxChgModel;
                __block RHDevDataModel *maxDchgModel;
                [self.dataArr enumerateObjectsUsingBlock:^(RHDevEMSModel  *_Nonnull emsModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    emsModel.data = dic;
                    [emsModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
                        if([dataModel.keyCode isEqualToString:@"Bty_MaxChgCur"]){
                            maxChgModel = dataModel;
                        }
                        if([dataModel.keyCode isEqualToString:@"Bty_MaxDischgCur"]){
                            maxDchgModel = dataModel;
                        }
                    }];
                    
                }];
                
                //电池组最大可充电功率
                double chg = [ValidNullData(dic[@"Bty_MaxChgCur"]) doubleValue] * [ValidNullData(dic[@"Bty_TV"]) doubleValue];
                maxChgModel.content = [[NSNumber numberWithDouble:chg]twoDecimalPlacesWithoutRounding];
                //电池组最大可放电功率
                double dchg = [ValidNullData(dic[@"Bty_MaxDischgCur"]) doubleValue] * [ValidNullData(dic[@"Bty_TV"]) doubleValue];
                maxDchgModel.content = [[NSNumber numberWithDouble:dchg]twoDecimalPlacesWithoutRounding];
                
                [self.tableView reloadData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
    
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    RHDevEMSModel *emsModel = self.dataArr[section];
    return emsModel.infoArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    RHDevEMSModel *emsModel = self.dataArr[section];
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 50)];
    headerView.backgroundColor = CFTabViewBgColor;
    
    UIView *containView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 50)];
    [headerView addSubview:containView];
    containView.layer.cornerRadius = 8;
    containView.layer.masksToBounds = YES;
    containView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    containView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:emsModel.icon]];
    [containView addSubview:icon];
    
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kSYSTEMFONT(15);
    titleLab.textColor = kCOLOR_HEX(@"3F4443");
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = emsModel.title.rh_localized;
    [containView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [containView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *containView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    containView.backgroundColor = CFTabViewBgColor;
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, containView.width-30, 10)];
    subView.backgroundColor = [UIColor whiteColor];
    subView.layer.cornerRadius = 8;
    subView.layer.masksToBounds = YES;
    subView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [containView addSubview:subView];
    return containView;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHCommonDataCell *cell;
    RHDevEMSModel *emsSectionModel = self.dataArr[indexPath.section];
    RHDevDataModel *dataModel = emsSectionModel.infoArr[indexPath.row];
    NSInteger celltype = dataModel.type ;
    if(celltype == CommonCellTypeNormal){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    }else if (celltype == CommonCellTypeStatus){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonStatusCell];
    }else if (celltype == CommonCellTypeIndicator){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonIndicatorCell];
    }else if (celltype == CommonCellTypeProgress){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonProgressCell];
    }
    cell.dataModel = dataModel;
    return cell;

}


@end
